#include "viml/compiler.h"
#include "viml/vm.h"
#include "viml/value.h"
#include <gtest/gtest.h>
#include <iostream>

namespace viml {

class WhileLoopTest : public ::testing::Test {
protected:
    void SetUp() override {
        // Setup code if needed
    }

    void TearDown() override {
        // Cleanup code if needed
    }
};

// 测试基本的while循环
TEST_F(WhileLoopTest, BasicWhileLoop) {
    Compiler compiler;
    VM vm;
    
    // 测试代码: let i = 0; while i < 3; echo i; let i = i + 1; endwhile
    std::string source = R"(
        let i = 0
        while i < 3
            echo i
            let i = i + 1
        endwhile
    )";
    
    try {
        auto bytecode = compiler.compile(source);
        Value result = vm.execute(bytecode);
        // 验证执行成功
        EXPECT_TRUE(true);
    } catch (const std::exception& e) {
        FAIL() << "Compilation or execution failed: " << e.what();
    }
}

// 测试条件始终为假的while循环
TEST_F(WhileLoopTest, WhileLoopWithFalseCondition) {
    Compiler compiler;
    VM vm;
    
    // 测试代码: let i = 5; while i < 3; echo i; let i = i + 1; endwhile
    std::string source = R"(
        let i = 5
        while i < 3
            echo i
            let i = i + 1
        endwhile
    )";
    
    try {
        auto bytecode = compiler.compile(source);
        Value result = vm.execute(bytecode);
        // 验证执行成功，循环体不应执行
        EXPECT_TRUE(true);
    } catch (const std::exception& e) {
        FAIL() << "Compilation or execution failed: " << e.what();
    }
}

// 测试嵌套while循环
TEST_F(WhileLoopTest, NestedWhileLoop) {
    Compiler compiler;
    VM vm;
    
    // 测试代码: let i = 0; while i < 2; let j = 0; while j < 2; echo i, j; let j = j + 1; endwhile; let i = i + 1; endwhile
    std::string source = R"(
        let i = 0
        while i < 2
            let j = 0
            while j < 2
                echo i, j
                let j = j + 1
            endwhile
            let i = i + 1
        endwhile
    )";
    
    try {
        auto bytecode = compiler.compile(source);
        Value result = vm.execute(bytecode);
        // 验证执行成功
        EXPECT_TRUE(true);
    } catch (const std::exception& e) {
        FAIL() << "Compilation or execution failed: " << e.what();
    }
}

// 测试空while循环体
// TEST_F(WhileLoopTest, EmptyWhileLoopBody) {
//     Compiler compiler;
//     VM vm;
    
//     // 测试代码: let i = 0; while i < 3; endwhile
//     std::string source = R"(
//         let i = 0
//         while i < 3
//         endwhile
//     )";
    
//     try {
//         auto bytecode = compiler.compile(source);
//         Value result = vm.execute(bytecode);
//         // 验证执行成功
//         EXPECT_TRUE(true);
//     } catch (const std::exception& e) {
//         FAIL() << "Compilation or execution failed: " << e.what();
//     }
// }

} // namespace viml